<template>
  <div>
    <div class="app-container">
      <el-form
        :model="queryParams"
        ref="queryRef"
        v-show="showSearch"
        :inline="true"
      >
        <el-form-item label="回收编码" prop="recycleCode">
          <el-input
            v-model="queryParams.recycleCode"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品类目" prop="category">
          <el-select
            v-model="queryParams.category"
            filterable
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择商品类目"
            style="width: 180px"
          >
            <el-option
              v-for="item in goods_category"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-select
            v-model="queryParams.brand"
            filterable
            reserve-keyword
            clearable
            style="width: 230px"
            allow-create
            default-first-option
            placeholder="请选择品牌"
          >
            <el-option
              v-for="item in item_brand"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品编码" prop="ref">
          <el-input
            v-model="queryParams.ref"
            placeholder="请输入"
            style="width: 230px"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品型号" prop="model">
          <el-input
            v-model="queryParams.model"
            placeholder="请输入商品型号"
            clearable
            style="width: 230px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="itemStatusList">
          <el-select
            v-model="queryParams.itemStatusList"
            placeholder="状态"
            style="width: 110px"
            clearable
            multiple
          >
            <el-option
              v-for="i in item_status"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="回收价格" prop="recyclePrice">
          <el-input
            v-model="queryParams.recyclePrice"
            placeholder="请输入"
            style="width: 230px"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="回收人" prop="recyclePersonId">
          <el-select
            v-model="queryParams.recyclePersonId"
            filterable
            remote
            reserve-keyword
            placeholder="请选择回收人"
            :remote-method="getUserOption"
            :loading="userLoading"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="入库时间">
          <el-date-picker
            v-model="warehouseEntryTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            style="width: 230px"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="打款时间">
          <el-date-picker
            v-model="recycleTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            style="width: 230px"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleQuery"
            v-hasPermi="['erp:skesPurchase:query']"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Coin"
            @click="handleQrcode"
            v-hasPermi="['erp:skesPurchase:qrcode']"
            >批量生成二维码</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Upload"
            @click="handleAdd"
            v-hasPermi="['erp:skesPurchase:add']"
            >入库</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            :disabled="!imgList.length || printDisabled"
            type="success"
            plain
            icon="Printer"
            @click="handlePrint"
            >打印</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['erp:skesPurchase:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        height="58vh"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="品牌" prop="brand" align="center">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.brand"
              :options="item_brand"
              :value="scope.row.brand"
            />
            <span v-else>{{ scope.row.brandName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回收编码" prop="recycleCode" align="center" />
        <el-table-column label="商品编码" prop="ref" align="center" />
        <el-table-column label="商品型号" prop="model" align="center" />
        <el-table-column label="快递单号" prop="expressNo" align="center" />
        <el-table-column label="回收价格" prop="recyclePrice" align="center" />
        <el-table-column
          label="商品正面图"
          prop="watchImageUrl"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrl"
                :preview-src-list="[scope.row.watchImageUrl]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="商品背面图"
          prop="watchImageUrlBack"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrlBack"
                :preview-src-list="[scope.row.watchImageUrlBack]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品状态" prop="itemStatus" align="center">
          <template #default="scope">
            <dict-tag :options="item_status" :value="scope.row.itemStatus" />
          </template>
        </el-table-column>
        <el-table-column
          label="二维码"
          prop="imgUrl"
          align="center"
          width="150"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 120px">
              <el-image
                :src="scope.row.imgUrl"
                :preview-src-list="[scope.row.imgUrl]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品类目" prop="category" align="center">
          <template #default="scope">
            <dict-tag :options="goods_category" :value="scope.row.category" />
          </template>
        </el-table-column>
        <el-table-column
          label="打款时间"
          prop="paymentTime"
          align="center"
          width="100"
        />
        <el-table-column label="打款状态" prop="paymentStatus" align="center">
          <template #default="scope">
            <dict-tag
              :options="payment_status"
              :value="scope.row.paymentStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="回收人用户名"
          prop="recyclePersonName"
          width="130"
          align="center"
        />
        <el-table-column
          label="回收人昵称"
          prop="recyclePerson"
          align="center"
          width="100"
        />
        <el-table-column
          label="回收客户"
          prop="recycleCustomer"
          align="center"
        />
        <el-table-column
          label="商品退货状态"
          prop="goodsStatus"
          align="center"
          width="130"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.goodsStatus"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          align="center"
          width="200"
        />
        <el-table-column
          label="入库时间"
          prop="warehouseEntryTime"
          align="center"
          width="100"
        />
        <el-table-column label="运费" prop="expressFee" align="center" />
        <el-table-column label="库位" prop="locationNo" align="center" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="160"
        >
          <template #default="scope">
            <el-tooltip
              content="入库"
              placement="top"
              v-if="scope.row.roleId !== 1"
            >
              <el-button
                link
                type="primary"
                icon="Download"
                @click="handleAdd(scope.row)"
                v-hasPermi="['erp:skesPurchase:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="上传图片" placement="top">
              <el-button
                link
                type="primary"
                icon="Upload"
                @click="handleUpload(scope.row)"
                v-hasPermi="['erp:skesPurchase:upload']"
              ></el-button>
            </el-tooltip>
            <el-tooltip
              content="修改"
              placement="top"
              v-if="scope.row.roleId !== 1"
            >
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['erp:skesPurchase:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="生成二维码" placement="top">
              <el-button
                type="primary"
                link
                icon="Coin"
                @click="handleQrcodeAlone(scope.row.itemId)"
                v-hasPermi="['erp:skesPurchase:qrcode']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="(scope.row.locationNo ? '取消': '') + '分配库位'" placement="top">
              <el-button
                :style="scope.row.locationNo ? 'transform: rotate(180deg);': ''"
                type="primary"
                link
                :icon="'Pointer'"
                @click="handleAllocateLocation(scope.row)"
                v-hasPermi="['erp:skesPurchase:allocate']"
              ></el-button>
            </el-tooltip>

            <!-- <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['erp:skesPurchase:remove']"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="footer-msg">
        <p>
          <i class="el-icon-warning blue-text"></i>
          数量总和:
          <span class="blue-text">{{ summaryInfo.sumCount || "N/A" }}</span>
        </p>
        <p>
          成本金额:<span class="blue-text">{{
            summaryInfo.sumAmount || "N/A"
          }}</span>
        </p>
        <p>
          邮费金额总和:<span class="blue-text">{{
            summaryInfo.sumExpressFeeAmount || "N/A"
          }}</span>
        </p>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <add
      v-model:visible="addParams.visible"
      :params="addParams"
      :options="payment_status"
      @refresh="getList"
    />
    <print
      ref="printRef"
      @print-success="printSuccess"
      :imgList="imgList"
    ></print>
    <!-- 上传图片 -->
    <el-dialog
      title="图片上传"
      v-model="uploadImage"
      width="500px"
      append-to-body
      :before-close="clearImg"
    >
      <el-form :inline="true">
        <el-form-item label="商品正面" prop="file">
          <el-upload
            v-model:file-list="fileList"
            ref="upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :limit="1"
            :on-exceed="handleExceed"
            accept=".jpg,.png,.jpeg"
            :auto-upload="false"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品背面" prop="file">
          <el-upload
            v-model:file-list="fileListBack"
            ref="upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :limit="1"
            :on-exceed="handleExceed"
            accept=".jpg,.png,.jpeg"
            :auto-upload="false"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUpload">确 定</el-button>
          <el-button @click="clearImg">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Recycle">
import print from "./print.vue";
import {
  listTable,
  delRegister,
  retry,
  refund,
  uploadApi,
  qrcode,
  batchQrcode,
  allocateLocation,
  cancelAllocateLocation
} from "@/api/purchase/register";
import { userOptionSelect } from "@/api/system/user";
import Add from "./add.vue";
import { ElFormItem, ElSelect, ElOption, ElMessageBox, ElRadioGroup, ElRadio } from "element-plus";
import { h } from "vue";

const { proxy } = getCurrentInstance();
const dataList = ref([]);
const selectionData = ref([]);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const summaryInfo = ref({});
const printList = ref([]);

const recycleTime = ref([]);
const warehouseEntryTime = ref([]);
const paymentTime = ref([]);
const {
  payment_status,
  goods_category,
  goods_status,
  item_brand,
  item_status,
  location_status
} = proxy.useDict(
  "payment_status",
  "goods_category",
  "goods_status",
  "item_brand",
  "item_status",
  "location_status"
);
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const addParams = ref({
  type: "add",
  visible: false,
  id: undefined,
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    model: undefined,
    ref: undefined,
    itemStatusList: undefined,
    category: undefined,
    recyclePrice: undefined,
    recyclePerson: undefined,
  },
});
const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  const [beginRecycleTime, endRecycleTime] = recycleTime.value;
  const [beginWarehouseEntryTime, endWarehouseEntryTime] =
    warehouseEntryTime.value;
  const [beginPaymentTime, endPaymentTime] = paymentTime.value;
  const params = {
    beginRecycleTime,
    endRecycleTime,
    beginWarehouseEntryTime,
    endWarehouseEntryTime,
    beginPaymentTime,
    endPaymentTime,
  };
  listTable({
    ...queryParams.value,
    params,
    itemStatusList:
      queryParams.value.itemStatusList &&
      queryParams.value.itemStatusList.join(","),
  }).then((response) => {
    dataList.value = response.rows;
    total.value = response.total;
    summaryInfo.value = { ...response, rows: undefined };
    loading.value = false;
  });
}
/** 商品状态修改 */
async function handleStatusChange(row) {
  loading.value = true;
  if (row.goodsStatus === 1) {
    proxy.$modal
      .confirm("禁用商品,该商品的所有提成会被清空,请谨慎操作")
      .then(function () {
        return refund(row.itemId);
      })
      .then(() => {
        proxy.$modal.msgSuccess("禁用" + "成功");
        loading.value = false;
      })
      .catch(function () {
        row.goodsStatus = row.goodsStatus === 0 ? 1 : 0;
        loading.value = false;
      });
  } else {
    await retry(row.itemId);
    proxy.$modal.msgSuccess("启用成功");
    loading.value = false;
  }
}
/** 图片上传 */
const uploadParams = ref();
const fileList = ref([]);
const fileListBack = ref([]);
const uploadImage = ref(false);
const uploadRef = ref();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
function handleUpload(row) {
  const { itemId, model } = row;
  uploadParams.value = {
    itemId,
    model,
  };
  uploadImage.value = true;
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const handleExceed = (files) => {
  uploadRef.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadRef.value.handleStart(file);
};
function clearImg() {
  uploadParams.value = {};
  fileList.value = [];
  fileListBack.value = [];
  uploadImage.value = false;
}
async function submitUpload() {
  const formData = new FormData();
  formData.append(
    "files",
    (fileList.value[0] && fileList.value[0].raw) || undefined
  );
  formData.append(
    "files",
    (fileListBack.value[0] && fileListBack.value[0].raw) || undefined
  );
  const { itemId, model } = uploadParams.value;
  formData.append("itemId", itemId);
  formData.append("model", model);
  await uploadApi(formData);
  proxy.$modal.msgSuccess("上传商品图片成功");
  getList();
  clearImg();
}
/** 打印图片 */
const printDisabled = ref(false);
const imgList = ref([]);
const printRef = ref();
function handlePrint() {
  printDisabled.value = true;
  printRef.value.handlePrint();
}
function printSuccess() {
  printDisabled.value = false;
}
/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: userId,
        label: `${userId},${nickName},${userName}`,
        nickName: i.nickName,
      };
    });
    userLoading.value = false;
  }
}
getUserOption(" ");
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  recycleTime.value = [];
  warehouseEntryTime.value = [];
  paymentTime.value = [];
  handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
  const [beginRecycleTime, endRecycleTime] = recycleTime.value;
  const [beginWarehouseEntryTime, endWarehouseEntryTime] =
    warehouseEntryTime.value;
  const [beginPaymentTime, endPaymentTime] = paymentTime.value;
  const params = {
    beginRecycleTime,
    endRecycleTime,
    beginWarehouseEntryTime,
    endWarehouseEntryTime,
    beginPaymentTime,
    endPaymentTime,
  };
  proxy.download(
    "purchase/register/export",
    {
      ...queryParams.value,
      itemStatusList:
        queryParams.value.itemStatusList &&
        queryParams.value.itemStatusList.join(","),
      params,
    },
    `recycle_${new Date().getTime()}.xlsx`
  );
}
/** 删除按钮操作 */
function handleDelete(row) {
  let ids = [],
    brands = [];
  if (row.id) {
    ids = row.id;
    brands = row.brand;
  } else {
    selectionData.value.forEach((i) => {
      ids.push(i.id);
      brands.push(i.brand);
    });
    ids = ids.join(",");
    brands = brands.join(",");
  }
  proxy.$modal
    .confirm('是否确认删除商品"' + brands + '"的数据项?')
    .then(function () {
      return delRegister(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

async function handleQrcode() {
  const vals = Object.values(queryParams.value);
  if (vals.every((i) => !i) && !selectionData.value.length) {
    proxy.$modal.msgError("请选择商品或查询条件后重试");
    return;
  }
  try {
    loading.value = true;
    if (selectionData.value.length) {
      await batchQrcode({
        itemIds: selectionData.value.map((i) => i.itemId),
      });
    } else {
      await batchQrcode({
        ...queryParams.value,
        itemStatusList:
          queryParams.value.itemStatusList &&
          queryParams.value.itemStatusList.join(","),
        pageNum: undefined,
        pageSize: undefined,
        params: undefined,
      });
    }
    proxy.$modal.msgSuccess("生成二维码成功");
    getList();
  } finally {
    loading.value = false;
  }
}
async function handleQrcodeAlone(itemId) {
  try {
    loading.value = true;
    await qrcode(itemId);
    proxy.$modal.msgSuccess("生成二维码成功");
    getList();
  } finally {
    loading.value = false;
  }
}

function handleAllocateLocation(row) {
  const id = row.itemId;
  const locationNo = row.locationNo;

  const shelfStatus = ref(location_status.value?.[0]?.value)

  const msg = locationNo ? `确认取消分配库位吗?` :  () =>
        h('div', {style: {padding: '0 16px'}}, [
          h('div', {style: {fontWeight: 600, fontSize: '14px', marginBottom: '8px'}}, '请选择分配库位'),
          h(
            'div',
            [
              h(
              ElRadioGroup,
              {
                modelValue: shelfStatus.value,
                onChange: (e => shelfStatus.value = e),
              },
              location_status.value.map((item) =>
                h(ElRadio, {
                  key: item.value,
                  value: item.value,
                }, item.label)
              )
            )]
				)])
  ElMessageBox
		.confirm(msg, "系统提示", {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: locationNo ? 'warning' : '',
    })
		.then(function () {

			return locationNo ?  cancelAllocateLocation({itemId: id, locationNo}) : allocateLocation(id, shelfStatus.value)
		})
		.then(() => {
			getList()
			proxy.$modal.msgSuccess(`${locationNo ? '取消': ''}分配库位成功`)
		})
		.catch(() => {})
}
/** 添加商品*/
function handleAdd(row) {
  if (!row.id && !selectionData.value.length) {
    proxy.$modal.msgError("请选择要入库的商品");
    return;
  } else if (selectionData.value.length > 1) {
    proxy.$modal.msgError("请只选择一个商品");
    return;
  }
  const id = row.itemId ? row.itemId : selectionData.value[0].itemId;
  addParams.value = {
    id,
    type: "add",
    visible: true,
  };
}
/** 修改商品*/
function handleUpdate(row) {
  addParams.value = {
    type: "edit",
    visible: true,
    id: row.itemId,
  };
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectionData.value = selection;
  imgList.value = selection.map((i) => i.imgUrl);
}
getList();
</script>
